#pragma once
#include <stdio.h>
#include <assert.h>
#include <iostream>

namespace ssy
{
	template <typename T>
	class vector
	{
	public:
		typedef T* iterator;
		typedef const T* const_iterator;

		vector()
			:_start(nullptr)
			,_finish(nullptr)
			,_end_of_storage(nullptr)
		{}

		~vector()
		{
			if (_start)
			{
				delete[] _start;
				_start = nullptr;
				_finish = nullptr;
				_end_of_storage = nullptr;
			}
		}

		//reserve改变容量，可大可小
		void reserve(int n)
		{
			if (n > capacity())
			{
				iterator tmp = new T[n];
				int sz = size();

				if (_start)
				{
					memcpy(tmp, _start, sizeof(T) * sz);
					delete[] _start;
				}

				_start = tmp;
				_finish = _start + sz;
				_end_of_storage = _start + n;
			}
			
		}

		void push_back(const T& x)
		{
			if (_finish == _end_of_storage)
			{
				reserve(capacity() == 0 ? 4 : 2 * capacity());
			}

			*_finish = x;
			++_finish;

		}

		//迭代器
		iterator begin()
		{
			return _start;
		}

		iterator end()
		{
			return _finish;
		}

		const_iterator begin() const
		{
			return _start;
		}

		const_iterator end() const
		{
			return _finish;
		}


		size_t size() const
		{
			return _finish - _start;
		}

		size_t capacity() const
		{
			return _end_of_storage - _start;
		}

		
		//中括号
		const T& operator[](size_t pos) const
		{
			assert(pos < size());
			return _start[pos];
		}
		T& operator[](size_t pos)
		{
			assert(pos < size());
			return _start[pos];
		}

		iterator insert(iterator pos, const T& x)
		{
			assert(pos <= _finish && pos >= _start);

			if (_finish == _end_of_storage)
			{
				size_t pp = pos - _start;
				size_t newcapacity = capacity() == 0 ? 4 : 2 * capacity();
				reserve(newcapacity);
				pos = _start + pp;
			}

			iterator end = _finish - 1;
			while (end >= pos)
			{
				*(end + 1) = *end;
				--end;
			}

			*pos = x;
			++_finish;

			return pos;
		}

		void erase(iterator pos)
		{
			assert(pos >= _start && pos < _finish);

			
			while (pos < _finish)
			{
				*pos = *(pos + 1);
				++pos;
			}

			--_finish;
		}

	private:

		iterator _start;
		iterator _finish;
		iterator _end_of_storage;
	};


	void print(const vector<int>& v)
	{
	/*	for (int i = 0;i<v.size();i++)
		{
			std::cout << v[i] << " ";
		}*/

		for (auto ch : v)
		{
			std::cout << ch << " ";
		}

		std::cout << std::endl;
	}
	
}